//
//  RGMessageContactVC.m
//  RedGrass
//
//  Created by wuyine on 2018/12/6.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGMessageContactVC.h"
#import "RGMessageContactCell.h"
#import "RGMessageInterfaceBulider.h"
#import "RGMessageContactModel.h"
#import "RGChatViewController.h"


@interface RGMessageContactVC ()<UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UISearchController *searchController;
//数据源
@property (strong,nonatomic) NSMutableArray  *dataList;
@property (strong,nonatomic) NSMutableArray  *searchList;
@end

@implementation RGMessageContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customNavBar.title = @"联系人";
    [self showBackButton];
    self.definesPresentationContext = YES;
    [self initUI];
    [self addMasonry];
    
    [self loadData];
}

- (void)loadData {
    HttpRequest *quest = [HttpRequest buildRequest:url_linkman];
    NSDictionary *params = [RGMessageInterfaceBulider buildLinkman];
    AA_WEAK_MAKE(self) weakSelf = self;
    [quest post:params success:^(id data) {
        [weakSelf dismissLoading];
        NSArray *userFollow = [RGMessageContactModel arrayOfModelsFromDictionaries:[data objectForKey:@"userFollow"] error:nil];
        NSArray *goodFriend = [RGMessageContactModel arrayOfModelsFromDictionaries:[data objectForKey:@"goodFriend"] error:nil];
        [weakSelf.dataList replaceObjectAtIndex:1 withObject:userFollow.count>0?userFollow:[NSArray new]];
        [weakSelf.dataList replaceObjectAtIndex:0 withObject:goodFriend.count>0?goodFriend:[NSArray new]];
        [weakSelf.tableView reloadData];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf showTextMessageWithMessage:message];
    }];
}

- (void)initUI {
    self.customContentView.backgroundColor = [UIColor blackColor];
    [self.customContentView addSubview:self.tableView];
}

- (void)addMasonry {
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF.nickname CONTAINS[c] %@", searchString];
    NSArray *sec0 = [[self.dataList objectAtIndex:0] filteredArrayUsingPredicate:preicate];
    if (sec0.count > 0) {
        [self.searchList replaceObjectAtIndex:0 withObject:sec0];
    }else {
        [self.searchList replaceObjectAtIndex:0 withObject:[NSArray new]];
    }
    NSArray *sec1 = [[self.dataList objectAtIndex:1] filteredArrayUsingPredicate:preicate];
    if (sec1.count > 0) {
        [self.searchList replaceObjectAtIndex:1 withObject:sec1];
    }else {
        [self.searchList replaceObjectAtIndex:1 withObject:[NSArray new]];
    }
    //刷新表格
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSArray *list;
    if (self.searchController.isActive) {
        list = [self.searchList objectAtIndex:section];
    }else {
        list = [self.dataList objectAtIndex:section];
    }
    if (list.count > 0) {
        return 40;
    }else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 40)];
    header.backgroundColor = [UIColor blackColor];
    UILabel *title = [[UILabel alloc] init];
    title.font = FONT(customFontName, 14);
    title.textColor = UICOLOR_WITH_RGBINT(0xffffff);
    [header addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(20);
        make.centerY.mas_equalTo(0);
    }];
    if (section == 0) {
        title.text = @"好友";
    }else {
        title.text = @"全部关注";
    }
    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RGMessageContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"messageContactCell"];
    
    NSArray *arr;
    if(self.searchController.isActive){
        arr = [self.searchList objectAtIndex:indexPath.section];
    }else{
        arr = [self.dataList objectAtIndex:indexPath.section];
    }
  
    RGMessageContactModel *model = [arr objectAtIndex:indexPath.row];
    cell.model = model;
    AA_WEAK_MAKE(self)weakSelf = self;
    [cell setMessageBtnClickBlock:^{
        
        NSArray *arr;
        if(weakSelf.searchController.isActive){
            arr = [weakSelf.searchList objectAtIndex:indexPath.section];
        }else{
            arr = [weakSelf.dataList objectAtIndex:indexPath.section];
        }
        RGMessageContactModel *model = [arr objectAtIndex:indexPath.row];
        NSInteger userId = [RGUserInfoModel getUserInfo].ID;
        if(userId == model.ID){
            [weakSelf showTextMessageWithMessage:@"不能和自己发私信"];
        }else{
            RGChatViewController *vc = [[RGChatViewController alloc]init];
            vc.userId = [RGUserInfoModel getUserInfo].ID;
            vc.toUserId = model.ID;
            vc.nickName = model.nickname;
           
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *list;
    if (self.searchController.active) {
        list = [self.searchList objectAtIndex:section];
        return list.count;
    }else {
        list = [self.dataList objectAtIndex:section];
        return list.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 75;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    RGChatViewController *vc = [[RGChatViewController alloc]init];
//    NSArray *arr = [self.dataList objectAtIndex:indexPath.section];
//    RGMessageContactModel *model = [arr objectAtIndex:indexPath.row];
//    vc.userId = [RGUserInfoModel getUserInfo].ID;
//    vc.toUserId = model.ID;
//    vc.nickName = model.nickname;
//    [self.navigationController pushViewController:vc animated:YES];
    
}

////返回索引数组
//-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//    NSMutableArray *arr = [NSMutableArray new];
//    for (char c='A'; c<='Z'; c++) {
//        [arr addObject:[NSString stringWithUTF32Char:c]];
//    }
//    return arr;
//}
//
////响应点击索引时的委托方法
//-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
//    return 0;
//}



- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[RGMessageContactCell class] forCellReuseIdentifier:@"messageContactCell"];
        _tableView.tableFooterView = [UIView new];
        
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, self.searchController.searchBar.height)];
        [header addSubview:self.searchController.searchBar];
        _tableView.tableHeaderView = header;
        _tableView.backgroundColor = [UIColor blackColor];
        _tableView.sectionIndexColor = UICOLOR_WITH_RGBINT(0xcccccc);//设置默认时索引值颜色
        _tableView.sectionIndexTrackingBackgroundColor = [UIColor blackColor];//设置选中时，索引背景颜色
        _tableView.sectionIndexBackgroundColor = [UIColor blackColor];//设置默认时，索引的背景颜色
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        for(UIView *view in [_tableView subviews]) {
            if([[[view class] description] isEqualToString:@"UITableViewIndex"]) {
                [view setBackgroundColor:[UIColor blackColor]];
            }
        }
    }
    return _tableView;
}

- (UISearchController *)searchController {
    if (!_searchController) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        //设置代理
        _searchController.delegate = self;
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = NO;
        
        //设置UISearchController的显示属性，以下3个属性默认为YES
//        //搜索时，背景变暗色
//        _searchController.dimsBackgroundDuringPresentation = NO;
//        //搜索时，背景变模糊
//        _searchController.obscuresBackgroundDuringPresentation = NO;
//        //隐藏导航栏
//        _searchController.hidesNavigationBarDuringPresentation = NO;
        
        _searchController.searchBar.frame = CGRectMake(_searchController.searchBar.frame.origin.x, _searchController.searchBar.frame.origin.y, _searchController.searchBar.frame.size.width, 44.0);
        [_searchController.searchBar sizeToFit];
        [_searchController.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
        _searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
        _searchController.searchBar.placeholder = @"搜索用户备注或昵称";
        _searchController.searchBar.backgroundColor = UICOLOR_WITH_RGBINT(0x242730);
        _searchController.searchBar.barTintColor = UICOLOR_WITH_RGBINT(0x000000);
        _searchController.searchBar.tintColor = UICOLOR_WITH_RGBINT(0x999999);
    }
    return _searchController;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray new];
        [_dataList addObject:[NSArray new]];
        [_dataList addObject:[NSArray new]];
    }
    return _dataList;
}

- (NSMutableArray *)searchList {
    if (!_searchList) {
        _searchList = [NSMutableArray new];
        [_searchList addObject:[NSArray new]];
        [_searchList addObject:[NSArray new]];
    }
    return _searchList;
}
@end
